package com.daykw.xiaohongshu.task.thread;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.codehaus.plexus.util.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.impl.NutDao;

import com.daykw.xiaohongshu.http.HttpBase;
import com.daykw.xiaohongshu.model.TArticleTask;
import com.daykw.xiaohongshu.model.TAuthorTask;
import com.daykw.xiaohongshu.model.TKeywordNextTask;
import com.daykw.xiaohongshu.model.TSessionId;
import com.daykw.xiaohongshu.util.SessionUtils;
import com.daykw.xiaohongshu.util.SpringContextHolder;

import test.XiaoHongShuSign;

public class KeywordNextJobThreadPopu implements Runnable {

	private static Logger logger = Logger.getLogger(KeywordNextJobThreadApp.class);
	private TKeywordNextTask task;
	private String ip;
	private Integer port;
	private final static String REQUEST_ID = "dd633fd130f4edc18db5231513b748ed";

	public KeywordNextJobThreadPopu(TKeywordNextTask task) {
		this.task = task;
	}

	public KeywordNextJobThreadPopu(TKeywordNextTask task, String ip) {
		this.task = task;
		this.ip = ip.split(":")[0];
		this.port = Integer.valueOf(ip.split(":")[1]);
	}

	@Override
	public void run() {
		NutDao dao = SpringContextHolder.getBean("dao");
		try {
			dao.update(TKeywordNextTask.class, Chain.make("popu_status", 1), Cnd.where("id", "=", task.getId()));
			String k = java.net.URLEncoder.encode(task.getKeyword(), "utf-8");
			// http://www.xiaohongshu.com/web_api/sns/v2/search/note?keyword=%E6%9D%8E%E5%B0%8F%E7%92%90&page=2
			
			
//			GET https://www.xiaohongshu.com/wx_mp_api/sns/v1/search/notes?sid=session.1214697449282265726&keyword=%E4%B8%83%E5%A4%95%E7%A4%BC%E7%89%A9&sort=general&page=2&per_page=20 HTTP/1.1
//				Host: www.xiaohongshu.com
//				Content-Type: application/json
//				Accept: */*
//				User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 12_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/16A5339e MicroMessenger/6.7.1 NetType/WIFI Language/zh_CN
//				Referer: https://servicewechat.com/wxffc08ac7df482a27/68/page-frame.html
//				Accept-Language: zh-cn
//				Accept-Encoding: br, gzip, deflate

			//默认
			//https://www.xiaohongshu.com/api/sns/v8/search/notes?keyword=明玉&sort=&page=1&page_size=20&source=explore_feed&search_id=34A77ACAA2F909912C4D868972C757AE&platform=Android&deviceId=31748f62-7b7d-33f7-84d6-9b8959e393fa&device_fingerprint=201807031107247731f594d336e78c452aa2dece30b9930110abb793c305e3&device_fingerprint1=201807031107247731f594d336e78c452aa2dece30b9930110abb793c305e3&versionName=5.23.1&channel=BaiDu&sid=session.1215276526584162501&lang=zh-Hans&t=1535018538&sign=70adce4628671574543093f2f77f1175
			//时间 1 | 2
//			GET https://www.xiaohongshu.com/api/sns/v8/search/notes?keyword=%E9%9D%A2%E9%9C%9C&sort=time_descending&page=2&page_size=20&source=notes&search_id=E43D9CD05FFF8CF3A7CEB2019D0C14DD&platform=Android&deviceId=fa8265c4-f929-3900-90bf-ac6d321cc6ab&device_fingerprint=20180705144829b2d01289b09f5de74eb538aa504475320139e69c689426dc&device_fingerprint1=20180705144829b2d01289b09f5de74eb538aa504475320139e69c689426dc&versionName=5.23.0&channel=Store360&sid=session.1219282677194667089&lang=zh-Hans&t=1535214214&sign=334ce793d15caa5c338dd2cc485cda03 HTTP/1.1
			//  https://www.xiaohongshu.com/api/sns/v8/search/notes?keyword=面霜&sort=time_descending&page=1&page_size=20&source=explore_feed&search_id=4A7C63D3246A20532009E13C58EEFF4F&platform=Android&deviceId=fa8265c4-f929-3900-90bf-ac6d321cc6ab&device_fingerprint=20180705144829b2d01289b09f5de74eb538aa504475320139e69c689426dc&device_fingerprint1=20180705144829b2d01289b09f5de74eb538aa504475320139e69c689426dc&versionName=5.23.0&channel=Store360&sid=session.1219282677194667089&lang=zh-Hans&t=1535214745&sign=fa56eb766321bd1a56b63504fa16d37b
//				X-Tingyun-Id: LbxHzUNcfig;c=2;r=327558020;
//				Authorization: session.1219282677194667089
//				device_id: fa8265c4-f929-3900-90bf-ac6d321cc6ab
//				User-Agent: Dalvik/1.6.0 (Linux; U; Android 4.4.2; MI 6  Build/NMF26X) Resolution/720*1280 Version/5.23.0 Build/5230179 Device/(Xiaomi ;MI 6 )
//				shield: 
//				Host: www.xiaohongshu.com
//				Connection: Keep-Alive
//				Accept-Encoding: gzip
			//热度
//			GET https://www.xiaohongshu.com/api/sns/v8/search/notes?keyword=%E9%9D%A2%E9%9C%9C&sort=popularity_descending&page=1&page_size=20&source=explore_feed&search_id=0D2DA2EC788DA0214643BD73EE24FD13&platform=Android&deviceId=fa8265c4-f929-3900-90bf-ac6d321cc6ab&device_fingerprint=20180705144829b2d01289b09f5de74eb538aa504475320139e69c689426dc&device_fingerprint1=20180705144829b2d01289b09f5de74eb538aa504475320139e69c689426dc&versionName=5.23.0&channel=Store360&sid=session.1219282677194667089&lang=zh-Hans&t=1535214374&sign=6269ba1f33952c363b8df5d5ab489316 HTTP/1.1
//				X-Tingyun-Id: LbxHzUNcfig;c=2;r=274996883;
//				Authorization: session.1219282677194667089
//				device_id: fa8265c4-f929-3900-90bf-ac6d321cc6ab
//				User-Agent: Dalvik/1.6.0 (Linux; U; Android 4.4.2; MI 6  Build/NMF26X) Resolution/720*1280 Version/5.23.0 Build/5230179 Device/(Xiaomi ;MI 6 )
//				shield: 
//				Host: www.xiaohongshu.com
//				Connection: Keep-Alive
//				Accept-Encoding: gzip
			java.util.Calendar c = Calendar.getInstance();
			int dd = c.get(Calendar.DAY_OF_YEAR);
			//String sort= (dd%2==0) ?"time_descending":"popularity_descending";
			String sort="popularity_descending";
			TSessionId sid = SessionUtils.Session.session.getQueue();
			String subtring = "&sort="+sort+"&page="+task.getPage_index()+"&page_size=20&source=explore_feed&search_id="+getUUID()+"&platform=Android&deviceId="+sid.getDeviceId()+"&device_fingerprint="+sid.getDevice_fingerprint()+"&device_fingerprint1="+sid.getDevice_fingerprint()+"&versionName=5.23.0&channel=Store360&sid="+sid.getSid()+"&lang=zh-Hans&t="+System.currentTimeMillis();
			XiaoHongShuSign xhss = new XiaoHongShuSign();
			String sign = xhss.sign("keyword="+task.getKeyword()+subtring);
			
			String 	url="https://www.xiaohongshu.com/api/sns/v8/search/notes?keyword="+k+subtring+"&sign="+sign;
			HttpBase http = new HttpBase();
			Map<String, String> headers = new HashMap<String, String>();
//			headers.put("Host","www.xiaohongshu.com");
//			headers.put("Content-Type","application/json");
//			headers.put("Accept","*/*");
//			headers.put("X-Tingyun-Id","LbxHzUNcfig;c=2;r=1114698685;");
//			headers.put("Authorization","session.1220921136328762189");
//			headers.put("device_id","fa8265c4-f929-3900-90bf-ac6d321cc6ab");
//			headers.put("User-Agent","Mozilla/5.0 (iPhone; CPU iPhone OS 12_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/16A5339e MicroMessenger/6.7.1 NetType/WIFI Language/zh_CN");
//			headers.put("Referer","https://servicewechat.com/wxffc08ac7df482a27/68/page-frame.html");
//			headers.put("Accept-Language","zh-cn");
//			headers.put("Accept-Encoding","br, gzip, deflate");
			
			headers.put("accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
			headers.put("accept-encoding","gzip, deflate, br");
			headers.put("accept-language","zh-CN,zh;q=0.9,en;q=0.8");
			headers.put("cache-control","max-age=0");
			headers.put("upgrade-insecure-requests","1");
			headers.put("user-agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");
			
			
			// String html = http.request(url, "utf-8",
			// headers,ip,port).getResult();
			String html = http.get(url, "utf-8", headers, true);
			while ((StringUtils.isEmpty(html) || html.equals("fail"))
					|| (StringUtils.isNotEmpty(html) && html.indexOf("403 Forbidden") >= 0)) {
				//html = http.turl(url, "utf-8", headers, true);
				html = http.get(url, "utf-8", headers, true);
				//logger.error("################警告403 Forbidden IP封锁############");
				//dao.update(TKeywordNextTask.class, Chain.make("status", 3), Cnd.where("id", "=", task.getId()));
				//return;
			}
			
			if(html.equals("404")){
				dao.update(TKeywordNextTask.class, Chain.make("popu_status", 3), Cnd.where("id", "=", task.getId()));
				return;
			}
			
			JSONObject json = null;
			try {
				json = new JSONObject(html);
			} catch (Exception e) {
				dao.update(TKeywordNextTask.class, Chain.make("popu_status", 3), Cnd.where("id", "=", task.getId()));
				return;
			}

			JSONArray list = json.getJSONObject("data").getJSONArray("notes");
			int size = list.length();
			TArticleTask at;
			TAuthorTask aut;
			for (int i = 0; i < size; i++) {
				at = new TArticleTask();
				JSONObject d = list.getJSONObject(i);
				String aid = d.getString("id");
				if(StringUtils.isEmpty(aid) || aid.length() != 24){
					continue;
				}
				at.setAid(aid);
				at.setCreate_time(new Date());
				at.setComment_status(0);
				at.setStatus(0);
				// at.setTitle(d.getString("title"));
				at.setUrl("https://www.xiaohongshu.com/discovery/item/" + d.getString("id"));
				String user_id = d.getJSONObject("user").getString("userid");
				if(StringUtils.isEmpty(user_id) || user_id.length() != 24){
					continue;
				}
				at.setUser_id(user_id);
				try {
					dao.fastInsert(at);
				} catch (Exception e) {
					//dao.update(TArticleTask.class,Chain.make("comment_status", 0),Cnd.where("aid", "=",at.getAid()));
					// e.printStackTrace();
					// logger.error("插入TArticleTask失败.", e);
				}
				aut = new TAuthorTask();
				aut.setCreate_time(new Date());
				aut.setStatus(0);
				aut.setUser_id(user_id);
				try {
					dao.fastInsert(aut);
				} catch (Exception e) {
					// e.printStackTrace();
					// logger.error("插入TAuthorTask失败.", e);
				}
			}
			dao.update(TKeywordNextTask.class, Chain.make("popu_status", 2), Cnd.where("id", "=", task.getId()));
			logger.info("处理成功:"+url);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("处理TKeywordNextTask任务失败.", e);
			dao.update(TKeywordNextTask.class, Chain.make("popu_status", 3), Cnd.where("id", "=", task.getId()));
		}

	}
	
	public String getUUID() {
		return java.util.UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
	}

}
